﻿var ns = namespace("kaskelot.sp.ui");

ns.bemanningbemannaform = function () {
	var cookieName = "bemannaform-search";

	function init() {
		var c = kaskelot.sp.ui.cookies.getCookie(cookieName);
		if (c != undefined) {
			$("#InaktivaCheckbox").prop('checked', c.visaInaktiva);
			$("#PersonnummerTextbox").val(c.personnummer);
			$("#PostnummerTextbox").val(c.postnummer);
			$("#NamnTextbox").val(c.namn);
			$("#FunktionDropDown").val(c.funktionId).trigger("liszt:updated");
			$("#FritextTextbox").val(c.fritext);
			$("#VisaGrupp").prop('checked', c.visaGrupp);
			$("#VisaValdistrikt").prop('checked', c.visaValdistrikt);
			searchPerson();
		}

		$("#bemanna-search-button").click(
			function () {
				kaskelot.sp.ui.bemanningbemannaform.searchPerson();
			}
		);

		$("#bemanna-clear-button").click(
			function () {
				$("#InaktivaCheckbox").prop('checked', false);
				$("#PersonnummerTextbox").val("");
				$("#PostnummerTextbox").val("");
				$("#NamnTextbox").val("");
				$("#FunktionDropDown").val("").trigger("liszt:updated");
				$("#FritextTextbox").val("");
				$("#VisaGrupp").prop('checked', false);
				$("#VisaValdistrikt").prop('checked', false);
			}
		);

		$("#bemanna-form #bemanna-search-input-container").keypress(
			function (event) {
				if (event.which === 13) {
					kaskelot.sp.ui.bemanningbemannaform.searchPerson();
					event.stopPropagation();
				}
			}
		);
	}

	function showBemannaForm(vakansId, callback) {
		var selector = "#bemanna-form";
		kaskelot.sp.ui.formutils.getAndShowForm({
			params: {
				formName: "BemannaForm",
				idString: vakansId,
				parentIdString: ""
			},
			selector: selector,
			openFunction: function () {
				$(selector + " .chzn-select-deselect").chosen({ allow_single_deselect: true, disable_search: true });
			},
			okFunction: function () {
				$(selector).parent().block();

				var prog = kaskelot.sp.ui.formutils.getObject(selector);
				var data = "{\"form\":" + JSON.stringify(prog) + "}";

				var method = "BemannaVakans";

				$.ajax({
					url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientBemanningService.svc/" + method,
					data: data,
					type: "POST",
					processData: false,
					contentType: "application/json",
					dataType: "json",
					success: function (resp) {
						if (resp[method + "Result"].HasError) {
							kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
						}
						else if (resp[method + "Result"].HasWarning) {
							kaskelot.sp.ui.prompts.showPrompt({
								title: "Bekräfta",
								text: resp[method + "Result"].WarningMessage,
								okFunction: function () {
									prog.RemoveExisting = true;
									data = "{\"form\":" + JSON.stringify(prog) + "}";
									$.ajax({
										url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientBemanningService.svc/" + method,
										data: data,
										type: "POST",
										processData: false,
										contentType: "application/json",
										dataType: "json",
										success: function (resp) {
											if (resp[method + "Result"].HasError) {
												kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
											}
											else {
												$(selector).dialog("close");
												if (callback !== undefined) {
													callback();
												}
											}
										},
										error: function (xhr) {
											kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
										}
									});
									$(selector).dialog("close");
									if (callback !== undefined) {
										callback();
									}
								},
								cancelFunction: function () {
								$(selector).parent().unblock();
								}
							});
						}
						else {
							$(selector).dialog("close");
							if (callback !== undefined) {
								callback();
							}
						}
					},
					error: function (xhr) {
						kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
					}
				});
			}
		});
	}

	function searchPerson() {
		var inaktiva = $("#InaktivaCheckbox").prop('checked');
		var personnummer = $("#PersonnummerTextbox").val();
		var postnummer = $("#PostnummerTextbox").val();
		var namn = $("#NamnTextbox").val();
		var funktion = $("#FunktionDropDown").val();
		var fritext = $("#FritextTextbox").val();
		var grupp = $("#VisaGrupp").prop('checked');
		var valdistrikt = $("#VisaValdistrikt").prop('checked');
		var typ = $("#TypDropDown").val();

		var data = { namn: namn, personnummer: personnummer, postnummer: postnummer, fritext: fritext, funktionId: funktion, visaInaktiva: inaktiva, visaGrupp: grupp, visaValdistrikt: valdistrikt, typ: typ };
		kaskelot.sp.ui.cookies.setCookie(cookieName, data);

		$("#bemanna-form").block({ message: '<h1>Var god vänta...</h1>' });

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientBemanningService.svc/BemanningPersonSearch",
			type: "GET",
			data: data,
			processData: true,
			cache: false,
			success:
				function (data) {
					if (!data.BemanningPersonSearchResult.HasError) {
						$("#bemanna-search-results tbody").html(
							$("#bemanna-template").render(data.BemanningPersonSearchResult.Data)
						);

						for (var index = 0; index < $("a.person-link").length; index++) {
							var links = $("a.person-link");
							var id = links[index].id;

							var content = $("#personinfo-template").render(data.BemanningPersonSearchResult.Data[index]);

							$("#" + links[index].id).data("powertip", content);
							$("#" + links[index].id).powerTip({
								placement: 'w',
								fadeInTime: 500,
								smartPlacement: true,
								mouseOnToPopup: true
							});
						}
					}
					$("#bemanna-form").unblock();
				},
			error:
				function (xhr) {
					$("#bemanna-form").unblock();
					kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
				}
		});
	}

	function selectPerson(id) {
		$("#PersonId").val(id);
		$("#bemanna-results tr").removeClass("selected-row");
		$("#" + id).addClass("selected-row");
	}

	return {
		showBemannaForm: showBemannaForm,
		searchPerson: searchPerson,
		selectPerson: selectPerson,
		init: init
	};
}();